package com.link.base.base.message.controller;

import com.link.base.base.message.model.Message;
import com.link.base.base.message.model.MessageModuleNum;
import com.link.base.base.message.model.MessageTask;
import com.link.base.base.message.push.model.PushInfoInsert;
import com.link.base.base.message.push.service.PushService;
import com.link.base.base.message.service.MessageService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.query.Filter;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息管理 - 移动/WEB端数据展示接入
 *
 * @author ouyangzhenqiang
 * @date 2018/10/26
 */
@Controller
@RequestMapping("/link/pushNotice")
public class MessageController extends BasicController<Message> {

    @Resource
    private MessageService messageService;

    @Resource
    private PushService pushService;

    @Override
    public BasicService<Message> getBasicService() throws Exception {
        return messageService;
    }

    @Override
    public void beforQueryAllOrExample(Message entity, HttpServletRequest request) throws Exception {
        CoreUser user = UserUtil.getUser();
        if (entity.getUserId() == null) {
            Filter filter = new Filter("userId", String.valueOf(user.getId()));
            List<Filter> filterList = new ArrayList<Filter>();
            filterList.add(filter);
            entity.setFilterList(filterList);
        }
    }

    /**
     * 更新所有消息为已读
     *
     * @author yrf
     * @date 2018/10/27
     * @param message
     */
    @GetMapping("/readAll")
    @ResponseBody
    public Map<String, Object> readAll(@JsonParam Message message) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            message.setUserId(user.getId());
            messageService.readAllUpdate(message);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 移动端-移动端-查询消息各模块的未读数量，以及各消息模块最新一条推送记录内容和时间
     *
     * @author ouyangzhenqiang
     * @date 2018/10/27
     */
    @GetMapping(value = "/queryModuleUnReadCount", produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryModuleUnReadCount(MessageModuleNum record, HttpSession session,
                                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            record.setLogin(String.valueOf(user.getId()));
            List<MessageModuleNum> list = messageService.queryModuleUnReadCount(record);
            result.put("success", true);
            result.put("result", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 移动端-获取各消息模块最新一条推送记录内容和时间
     *
     * @author ouyangzhenqiang
     * @date 2018/10/27
     */
    @GetMapping(value = "/getLastMessageByModule", produces = "application/json")
    @ResponseBody
    public Map<String, Object> getLastMessageByModule(MessageModuleNum record, HttpSession session,
                                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            record.setLogin(String.valueOf(user.getId()));
            MessageModuleNum item = messageService.getLastMessageByModule(record);
            result.put("success", true);
            result.put("result", item);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 移动端-根据模块将该模块下所有未读消息设置为已读
     *
     * @author XYQ
     * 2017年9月25日
     */
    @GetMapping(value = "/setModuleReadedUpdate", produces = "application/json")
    @ResponseBody
    public Map<String, Object> setModuleReadedUpdate(@JsonParam Message record, HttpSession session, HttpServletRequest request,
                                                     HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String module = request.getParameter("module");
            if (StringUtils.isNotBlank(module)) {
                CoreUser user = UserUtil.getUser();
                record.setLogin(String.valueOf(user.getId()));
                record.setModule(module);
                messageService.setModuleReadedUpdate(record);
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 移动端-根据ID将未读消息更改为已读
     *
     * @author XYQ
     * 2017年10月23日
     */
    @GetMapping(value = "/setReadedById", produces = "application/json")
    @ResponseBody
    public Map<String, Object> setReadedById(HttpSession session, HttpServletRequest request,
                                             HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String id = request.getParameter("id");
            if (StringUtils.isNotBlank(id)) {
                CoreUser user = UserUtil.getUser();
                Message record = new Message();
                record.setLogin(String.valueOf(user.getId()));
                record.setId(Long.parseLong(id));
                messageService.setReadedById(record);
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 移动端-查询每个模块的消息记录数(包含已读和未读)
     *
     * @author XYQ
     * 2017年9月25日
     */
    @GetMapping(value = "/countByModule", produces = "application/json")
    @ResponseBody
    public Map<String, Object> countByModule(MessageModuleNum record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            record.setLogin(String.valueOf(user.getId()));
            int count = messageService.countByModule(record);
            result.put("success", true);
            result.put("count", count);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 移动端-查询指定模块、指定对象id的记录是否存在
     *
     * @author XYQ
     * 2017年10月12日
     */
    @GetMapping(value = "/queryExits", produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryExits(Message record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            record.setLogin(String.valueOf(user.getId()));
            List<Message> msg = messageService.queryExits(record);
            result.put("success", true);
            result.put("result", msg);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 移动端-根据objectID和模块删除一条记录
     *
     * @author XYQ
     * 2017年11月02日
     */
    @GetMapping(value = "/deleteByObjectId", produces = "application/json")
    @ResponseBody
    public Map<String, Object> deleteByObjectId(@JsonParam Message record, HttpSession session, HttpServletRequest request,
                                                HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            record.setLogin(String.valueOf(user.getId()));
            messageService.deleteByObjectId(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 查询消息列表下各模块列表的数据
     *
     * @author ouyangzhenqiang
     * @date 2018/10/28
     */
    @GetMapping(value = "/queryNoteListByExamplePage", produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryNoteListByExamplePage(MessageModuleNum record, HttpSession session, HttpServletRequest request,
                                                          HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            record.setLogin(String.valueOf(user.getId()));
            String module = record.getModule();
            String task = "task";
            String order = "order";
            String report = "report";
            String news = "news";
            String comment = "comment";
            String notice = "notice";
            String push = "push";
            String reception = "reception";
            if (task.equals(module)) {
                result.put("rows", messageService.queryTaskByExamplePage(record));
            } else if (order.equals(module)) {
                result.put("rows", messageService.queryOrderByExamplePage(record));
            } else if (report.equals(module)) {
                result.put("rows", messageService.queryReportByExamplePage(record));
            } else if (news.equals(module)) {
                result.put("rows", messageService.queryNewsByExamplePage(record));
            } else if (comment.equals(module)) {
                result.put("rows", messageService.queryCommentByExamplePage(record));
            } else if (notice.equals(module)) {
                result.put("rows", messageService.queryNoticeByExamplePage(record));
            } else if (push.equals(module) || reception.equals(module)) {
                result.put("rows", messageService.queryPushByExamplePage(record));
            } else {
                throw new Exception("模块不能为空.");
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<MessageTask>());
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 自主任务手动提醒
     *
     * @param entity
     * @return
     * @author 宋燕荣
     * @date 2019/8/19
     */
    @PostMapping({"/appMessageInsert"})
    @ResponseBody
    public Map<String, Object> appMessageInsert(@JsonParam PushInfoInsert entity) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            pushService.messageInsert(entity);
            result.put("success", true);
            result.put("code", "200");
        } catch (BasicServiceException e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
            result.put("code", e.getCode());
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("code", "400");
        }
        return result;
    }

    /**
     * PC端-根据ID将未读消息更改为已读
     *
     * @author XYQ
     * 2017年10月23日
     */
    @PostMapping(value = "/read", produces = "application/json")
    @ResponseBody
    public Map<String, Object> read(Message record,HttpSession session, HttpServletRequest request,
                                             HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String id = request.getParameter("id");
            if (StringUtils.isNotBlank(id)) {
                CoreUser user = UserUtil.getUser();
                record.setLogin(String.valueOf(user.getId()));
                messageService.setReadedById(record);
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

}
